package com.gg.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class ConcurrentUsers {
	 protected static ArrayList<ConcurrentUser> connections = 
		        new ArrayList<ConcurrentUser>();
	 
	 public void add(ConcurrentUser user) {
		 connections.add(user);
		 
	 }
	 
	 public void send(Account account, String message) throws IOException {
		
		List<ConcurrentUser> disconnectedList = new ArrayList<ConcurrentUser>();
		
		for (ConcurrentUser user : connections) {
			try {
				
				if(user.sameUser(account)) {
					user.send(message);					
				}
				
			} catch(UserDisconnectException e) {
				System.out.println(user.getId() + " disconnected!!");
				disconnectedList.add(user);
			}
		}
		
		connections.removeAll(disconnectedList);
	 }
}
